package com.java.study.common.utils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * 利用okhttp进行get和post的访问
 *
 * @author jiangli
 * @date 2019/10/13 12:58
 */

public class OKHttpUtil {

	/**
	 * get请求
	 *
	 * @param url
	 * @return
	 */
	public static Map<String, Object> httpGet(String url) {
		Map<String, Object> map = null;
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder().url(url).build();
		try {
			Response response = client.newCall(request).execute();
			String result = Objects.requireNonNull(response.body()).string();
			Gson gson = new Gson();
			map = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
			}.getType());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * post请求
	 *
	 * @param url
	 * @param data 提交的参数为key=value&key1=value1的形式
	 */
	public static String httpPost(String url, String data) {
		String result = null;
		OkHttpClient httpClient = new OkHttpClient();
		RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), data);
		Request request = new Request.Builder().url(url).post(requestBody).build();
		try {
			Response response = httpClient.newCall(request).execute();
			result = Objects.requireNonNull(response.body()).string();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

}